package com.solutionsfit.timesheet

import static javax.persistence.CascadeType.ALL
import static javax.persistence.EnumType.STRING

import javax.persistence.Enumerated
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Column
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.OneToMany
import javax.persistence.Table
import javax.persistence.Transient

@Entity
@Table(name="TIMESHEETS")
class GroovyTimesheet {
	@Id @GeneratedValue
	Long id
	
	@Column(name = "NATURAL_ID", unique = true)
	String naturalId
	
	@Enumerated(STRING)
	TimesheetStatus status
	
	@ManyToOne
	@JoinColumn(name = "PROJECT_ID")
	Project project
	
	@ManyToOne
	@JoinColumn(name = "USER_ID")
	User user
	
	@OneToMany(cascade = [ALL])
	@JoinColumn(name = "TIMESHEET_ID")
	List<GroovyTimeEntry> entries = new ArrayList<GroovyTimeEntry>()
	
	protected GroovyTimesheet() {}
	
	GroovyTimesheet(int month, int year, PayPeriodType payPeriod) {
		status = TimesheetStatus.UNSUBMITTED
		naturalId = "${month}-${year}-${payPeriod}"
		
		(payPeriod.getStartDate(month, year)..
				payPeriod.getEndDate(month, year)).each {
			entries << new GroovyTimeEntry(hours:0, date:it)
		}
	}
	
	void leftShift(GroovyTimeEntry entry) {
		entries << entry
	}
	
	void setHoursWorked(int index, BigDecimal hoursWorked) {
		getTimeEntry(date).hours = hoursWorked
	}

	@Transient
	Date getStartDate() {
		entries.get(0).date
	}
	
	@Transient
	GroovyTimeEntry getTimeEntry(int date) {
		entries.get(date - 1)
	}
	
	@Transient
	BigDecimal getTotalHoursWorked() {
		BigDecimal hoursWorked = 0
		
		entries.each
		{
			hoursWorked += it.hours
		}
		
		return hoursWorked
	}
	
	@Transient
	boolean isSubmitted() {
		return status != TimesheetStatus.UNSUBMITTED
	}
	
	String toString() {
		String result = "GroovyTimesheet"
		
		entries.each
		{
			if(result.length() > 0) result += ", "
			result += it
		}
		
		return result
	}
}